package com.laicunba.ext.web.filter;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class XSSFilter implements HandlerInterceptor {
	private static final Logger LOG = Logger.getLogger(XSSFilter.class);

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse response, Object arg2) throws Exception {
		if(req.getRequestURI().contains("/console/")){
			return true;
		}
		Iterator it = req.getParameterMap().values().iterator();
		String[] val = null;
		while (it.hasNext()) {
			val = (String[]) it.next();
			if (val.length > 0 && (val[0].contains("<") || val[0].contains(">"))) {
				LOG.warn(String.format("%s", val));

				response.setStatus(401);
				return false;
			}
		}
		return true;
	}

}
